/* 
 * Copyright [2018] [Alex/libo(liboms@hotmail.com)]
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.hyts.shell.executor;

import java.io.IOException;
import java.io.InputStream;
import java.util.Objects;
import java.util.Optional;
import java.util.logging.Logger;

import org.apache.commons.io.IOUtils;

import com.hyts.shell.cache.ICache;
import com.hyts.shell.cache.ICacheFactory;
import com.hyts.shell.config.SSHConfig;
import com.hyts.shell.error.SSHException;
import com.hyts.shell.executor.base.Executor;
import com.hyts.shell.handler.AbstractStreamHandler;
import com.hyts.shell.handler.BaseProcessStream;
import com.hyts.shell.model.ExecuteDomain;
import com.hyts.shell.model.ResultDomain;
import com.hyts.shell.model.StringResultDomain;
import com.hyts.shell.model.UserRealm;

import ch.ethz.ssh2.ChannelCondition;
import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.ConnectionInfo;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;

/**
 * @title BaseExcutor.java
 * @package com.hyts.shell.executor.base
 * @description TODO
 * @see TODO
 * @author libo/Alex
 * @email liboms@hotmail.com/liboware@163.com
 * @date 2018年5月17日
 * @version V1.0
 */
public class EthzExecutor implements Executor<ExecuteDomain,ResultDomain> {
	
	/**  
	 * <p>流处理器-抽象类</p> 
	 * @fieldName handler
	 * @fieldType AbstractStreamHandler
	 */ 
	AbstractStreamHandler handler = null;
	
	/**  
	 * <p>基础接口缓存操作</p> 
	 * @fieldName cache
	 * @fieldType ICache
	 */ 
	ICache cache = null;
	
	/**
	 * <p>
	 * 构建连接线程隔离操作
	 * </p>
	 * @fieldName connections
	 * @fieldType ThreadLocal<Connection>
	 */
	private static ThreadLocal<Connection> connections = new ThreadLocal<Connection>();

	/**
	 * <p>
	 * {字段的描述}
	 * </p>
	 * 
	 * @fieldName logger
	 * @fieldType Logger
	 */
	Logger logger = Logger.getLogger(EthzExecutor.class.getName());

	/**  
	 * @constructor：EthzExecutor  
	 * @param handler
	 * @param cache  
	 */ 
	public EthzExecutor(AbstractStreamHandler handler, ICache cache) {
		super();
		this.handler = handler;
		this.cache = cache;
	}

	/**  
	 * @constructor：SSH2Excecutor  
	 * @param handler  
	 */ 
	public EthzExecutor(AbstractStreamHandler handler) {
		super();
		this.handler = handler;
		cache = new ICacheFactory().getConnectionCacheManager();
	}
	
	/**  
	 * @constructor：SSH2Excecutor    
	 */ 
	public EthzExecutor() {
		super();
		this.handler = new BaseProcessStream();
		cache = new ICacheFactory().getConnectionCacheManager();
	}
	
	@Override
	public boolean login(UserRealm userDomain) throws SSHException {
		if (userDomain != null)
			new SSHException("不允许传入空得用户认证信息!");
		try {
			if (null == connections.get()) {
				build(userDomain);
			}
		} catch (IOException e) {
			throw new SSHException(e);
		}
		return true;
	}

	/**
	 * @throws IOException <b>build</b> <p>构建方法操作：构建Connection对象连接</p> @param
	 * conn @param domain @exception
	 */
	private void build(UserRealm domain) throws IOException {
		Connection conn = new Connection(domain.getIp(),
				domain.getPort() == null ? SSHConfig.DEFAULT_SSH_PORT : domain.getPort());
		ConnectionInfo info = conn.connect();
		logger.info("SSH连接信息:" + info.toString());
		conn.authenticateWithPassword(domain.getUserName(), domain.getPassword());
		connections.set(conn);
	}

	/**
	 * <b>getConnection</b> 
	 * <p>获取连接包含自动登录操作</p> 
	 * @param userDomain 
	 * @return @exception
	 */
	public Connection getConnection(UserRealm userDomain) {
		if (login(userDomain)) {
			return connections.get();
		}
		return null;
	}

	/*
	 * (非 Javadoc) 
	 * @param conn
	 * @return
	 * @see com.hyts.shell.executor.base.Executor#close(ch.ethz.ssh2.Connection)
	 * @exception
	 */
	@Override
	public boolean close() {
		Connection conn = connections.get();
		if (conn != null) {
			conn.close();
			connections.set(null);
			connections.remove();
		}
		return false;
	}

	
	/* (非 Javadoc)
	 * @param param
	 * @return
	 * @see com.hyts.shell.executor.base.Executor#execute(java.lang.Object)  
	 * @exception
	 */ 
	@Override
	public ResultDomain<String> execute(ExecuteDomain param) {
		InputStream stdOut = null;
		InputStream stdErr = null;
		String outStr = "";
		String outErr = "";
		int ret = -1;
		Session session = null;
		ResultDomain<String> domain = new StringResultDomain();
        try {
        	Connection conn = null;
        	if(cache.getValue(param) == null) {
        		conn = this.getConnection(param);
        		cache.putValue(param, conn);
        	}else {
        		System.out.println("读取缓存");
        		conn = (Connection) cache.getValue(param);
        	}
        	session = conn.openSession();
			session.execCommand(param.execCommand);
			stdOut = new StreamGobbler(session.getStdout());
			Object result1 = handler.processStream(stdOut, SSHConfig.DEFAULT_SSH_CHARSET);
			outStr = Objects.isNull(result1)?"":result1.toString();
			stdErr = new StreamGobbler(session.getStderr());
			Object result2 = handler.processStream(stdErr, SSHConfig.DEFAULT_SSH_CHARSET);
			outErr = Objects.isNull(result2)?"":result2.toString();
			session.waitForCondition(ChannelCondition.EXIT_STATUS, SSHConfig.TIME_OUT);
			domain.setExitStatus(session.getExitStatus());
			if(session.getExitStatus() == 0){
				domain.setSuccess(true);
			}else {
				domain.setSuccess(false);
			}
			domain.setResultSubject(outStr);
		} catch (IOException e) {
			e.printStackTrace();
			domain.setResultError(outErr);
			domain.setSuccess(false);
		} finally {
			if(session != null)
				session.close();
			IOUtils.closeQuietly(stdOut);
			IOUtils.closeQuietly(stdErr);
		}
        return domain;
	}
}
